﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Xml.Linq;
using EnvDTE;

namespace LuomgAddin
{
    class AddFileHeader : DTECommand
    {
        public AddFileHeader()
        {
            this.Text = "添加文件头";
            this.ToolTip = "为文件按照自定义模板创建文件头注释";
        }

        protected override void IntializeCore()
        {
            base.IntializeCore();
            {
                var events = this.DTE.Events.get_DocumentEvents() as DocumentEvents;
                events.DocumentSaved += OnDocumentSaved;
            }
        }

        private void OnDocumentSaved(Document document)
        {
            this.TryAddFileHeader(document, true);
        }

        protected override vsCommandStatus QueryStatusCore()
        {
            if (DTE.ActiveDocument != null) { return base.QueryStatusCore(); }

            return vsCommandStatus.vsCommandStatusSupported;
        }

        protected override void ExecuteCore()
        {
            var activeDoc = DTE.ActiveDocument;
            if (activeDoc != null)
            {
                this.TryAddFileHeader(activeDoc, false);
            }
        }

        private void TryAddFileHeader(Document activeDoc, bool alert)
        {
            var selection = activeDoc.Selection as TextSelection;
            if (selection != null)
            {
                var ac = selection.ActivePoint.AbsoluteCharOffset;
                selection.SelectAll();
                var t = selection.Text;
                selection.MoveToAbsoluteOffset(ac);

                if (!t.Trim().StartsWith("/*") && alert)
                {
                    var res = MessageBox.Show("当前文档还没有添加文件头，是否立即添加文件头？", Consts.提示, MessageBoxButton.YesNo);
                    if (res == MessageBoxResult.No) return;
                }

                var content = this.GetTemplate();

                selection.StartOfDocument();
                selection.Insert(content);

                selection.StartOfDocument();
                selection.FindText("$end$");
                selection.Delete();
            }
        }

        private string GetTemplate()
        {
            var dir = this.GetType().Assembly.CodeBase.Replace("file:///", string.Empty);
            var file = Path.Combine(Path.GetDirectoryName(dir), "LuomgAddin_FileHeaderTemplate.xml");
            if (!File.Exists(file))
            {
                // 源文件头信息：
                // <copyright file="IRepository.cs">
                // Copyright(c)2012-2013 GMFCN.All rights reserved.
                // CLR版本：4.0.30319.239
                // 开发组织：郭明锋@中国
                // 公司网站：http://www.gmfcn.net
                // 所属工程：GMF.Component.Data
                // 最后修改：郭明锋
                // 最后修改：2013/05/27 18:53
                // </copyright>

                File.WriteAllText(file, @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<FileHeaderTemplate>
    <NowFormat>yyyyMMdd</NowFormat>
    <Content>
        <![CDATA[/*******************************************************
 * 
 * Copyright(c)2012-2018 Luomg.All rights reserved.
 * CLR版本：.NET 4.0.0
 * 组织：罗敏贵@中国
 * 网站：http://luomingui.cnblogs.com
 * 说明：$end$
 *
 * 历史记录：
 * 创建文件 罗敏贵 $Now$
 * 
*******************************************************/
]]>
    </Content>
</FileHeaderTemplate>");
            }
            var xml = File.ReadAllText(file);

            var doc = XDocument.Load(new StringReader(xml));

            var nowFormat = doc.Descendants("NowFormat").First().Value;
            var content = doc.Descendants("Content").First().Value;

            var timeString = DateTime.Now.ToString(nowFormat);
            
            content = content.Replace("$Now$", timeString);
            
            return content;
        }
    }
}